package com.cloudcc.mobile.view.dynamic.dynamic;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.DynamicEvent;
import com.cloudcc.cloudframe.bus.EventList.FavotiteDynamicEvent;
import com.cloudcc.cloudframe.bus.EventList.VoteDynamicEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.model.DynamicModel;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreHandler;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreListViewContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.header.MaterialHeader;
import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.adapter.DynamicAdapter;
import com.cloudcc.mobile.entity.MyChatter;
import com.cloudcc.mobile.event.refresh.RefreshDynamicListEvent;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.DynamicControl;
import com.cloudcc.mobile.util.LoadingUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.MyWebActivity;
import com.cloudcc.mobile.view.activity.UserInfoActivity;
import com.cloudcc.mobile.view.dynamic.DynamicActivity;
import com.cloudcc.mobile.view.dynamic.RelevantActivtiy;
import com.cloudcc.mobile.view.main.fragment.BaseListFragment;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.IWebView;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;

/**
 * 动态页面
 * 
 * @author seven
 * 
 */
/**
 * @author seven
 * 
 */
public abstract class DynamicFragment extends BaseListFragment implements
		IEventLife, LoadMoreHandler,
		com.cloudcc.mobile.adapter.DynamicAdapter.OnItemListener, PtrHandler,
		OnItemClickListener {

	public static boolean hasCheckFrist = false;

	@Bind(R.id.listview)
	public ListView mListView;

	@Bind(R.id.load_more_list_view_ptr_frame)
	public PtrFrameLayout mRefreshLayout;

	@Bind(R.id.load_more_list_view_container)
	public LoadMoreListViewContainer mLoadMoreLayout;

	@Bind(R.id.introduction)
	RelativeLayout mmm;

	@Bind(R.id.in_know)
	TextView iKnow;

	protected DynamicControl mControl = new DynamicControl();

	protected DynamicAdapter mAdapter;
	

	@Override
	public void init() {
		initRefresh();
		initLoadMore();
		initRequestData();
	}

	/**
	 * 初始化刷新
	 */
	protected void initRefresh() {
		mRefreshLayout.setLoadingMinTime(1000);
		mRefreshLayout.setPtrHandler(this);

		final MyHeader header = new MyHeader(getActivity());
		int[] colors = getResources().getIntArray(R.array.google_colors);
		header.setColorSchemeColors(colors);
		header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
		header.setPadding(0, DensityUtils.dpToPixel(mContext, 10), 0,
				DensityUtils.dpToPixel(mContext, 5));
		header.setPtrFrameLayout(mRefreshLayout);
		mRefreshLayout.setHeaderView(header);
		mRefreshLayout.addPtrUIHandler(header);
	}

	/**
	 * 初始化 加载更多
	 */
	protected void initLoadMore() {
		mLoadMoreLayout.setAutoLoadMore(true);
		mLoadMoreLayout.setOffsetSize(3);
		mLoadMoreLayout.useDefaultFooter();
		mLoadMoreLayout.setLoadMoreHandler(this);
	}
	

	/**
	 *  自动开启刷新请求数据
	 */
	protected void initRequestData() {
		mRefreshLayout.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshLayout.autoRefresh(true);
			}
		}, 150);
	}

	@Override
	public void onLoadMore(LoadMoreContainer loadMoreContainer) {
		currentPage++;
		requestData();
	}

	@Override
	public void requestData() {
		mControl.getDynamic(currentPage, getQueryType());
	}

	public abstract String getQueryType();

	/**
	 * 加载 动态（微贴）成功的时候
	 * <p>
	 * #1   判断是不是 这类型 是自己的 不要操作 <br>
	 * #2  判断是不是出错 如果出错 判断是不是第一次访问 如果第一次访问的话 就 结束
	 * <p>
	 * 
	 * @param event
	 */
	public void onEventMainThread(DynamicEvent event) {

		if (!StringUtils.equals(getQueryType(), event.type)) {
			return;
		}
		if (event.isError()) {
			if (isFromRefresh()) {
				mRefreshLayout.refreshComplete();
				mLoadMoreLayout.loadMoreFinish(true, false);
			} else {
				mLoadMoreLayout.loadMoreError(1002, event.getMessage());
			}
			Toast.makeText(mContext, event.getMessage(), 0).show();
			return;
		}
		onRequestFinish(ListUtils.isEmpty(event.getData().data));
		if (mAdapter == null) {
			mAdapter = new DynamicAdapter(mContext);
			mListView.setAdapter(mAdapter);
			mListView.setOnItemClickListener(this);
			mAdapter.setOnItemtListener(this);
		}
		if (isFromRefresh()) {
			mAdapter.changeData(event.getData().data);
		} else {
			mAdapter.addData(event.getData().data);
		}
	}

	protected void onRequestFinish(boolean dataIsEmpty) {

		if (isFromRefresh()) {// 第一次加载 获得的数据为空
			mRefreshLayout.refreshComplete();
			mLoadMoreLayout.loadMoreFinish(dataIsEmpty, !dataIsEmpty);
		} else {
			mLoadMoreLayout.loadMoreFinish(false, !dataIsEmpty);
		}
	}

	@Override
	public void onClickCollect(DynamicModel t) {
		mControl.Favorite(t.id, t.isfavorited);
	}

	public void onEventMainThread(FavotiteDynamicEvent event) {
		//ToastMananger.getManager().showOk("结果::" + event.isOk());
	}

	@Override
	public void onClickLike(DynamicModel t, View v) {
		mControl.like(t.id, t.ispraised);
	}

	@Override
	public void onClickDelete(DynamicModel t, int pos) {

		if (StringUtils.equals(t.authorId,
				UserManager.getManager().getUser().userId)) {
			showDialog(t, pos);
		}

	}

	@Override
	public void onClickUser(DynamicModel t) {
		enterUserInfo(t);
	}

	private void enterUserInfo(DynamicModel t) {
		Intent intent = new Intent(getActivity(), UserInfoActivity.class);
		intent.putExtra(UserInfoActivity.KEY_USERID, t.authorId);
		startActivity(intent);
	}

	@Override
	public void onClickComment(DynamicModel t) {
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		Intent intent = new Intent(getActivity(), DynamicActivity.class);
		intent.putExtra("myChatter", covertBean);
		startActivity(intent);
	}

	@Override
	public void onClickDownload(DynamicModel t, int position) {
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		LoadingUtils loading = new LoadingUtils(mContext, covertBean, position);
		loading.loadingFile();
	}

	@Override
	public void onClickVote(DynamicModel t, String option) {
		
		createWainting();
		mControl.sendVote(t.id,option);
	}
	
	public void onEventMainThread(VoteDynamicEvent event){
		dismissWainting();
		
		mAdapter.refreshVote();
		
	}

	@Override
	public void onClickRelation(DynamicModel t) {
		AppContext.urlString = UrlManager.getRootUrl()+ UrlTools.getObjectUrl(t.targetId);
		Intent intent = new Intent(mContext, RelevantActivtiy.class);
		intent.putExtra("web", t.targetId);
		intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl(t.targetId));
		mContext.startActivity(intent);
	}

	@Override
	public void onClickBody(DynamicModel t) {
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		Intent intent = new Intent(getActivity(), DynamicActivity.class);
		intent.putExtra("myChatter", covertBean);
		startActivity(intent);
	}

	@Override
	public void onClickEventOrTask(DynamicModel t) {
		/*AppContext.urlString = UrlManager.APP_UR + "/"
				+ UrlTools.getTaskOrEventUrl(t.taskIdOrEventId);
		Intent intent = new Intent(mContext, RelevantActivtiy.class);
		intent.putExtra("web", t.taskIdOrEventId);
		intent.putExtra("web.url", AppContext.urlString);
		mContext.startActivity(intent);*/
		Intent intent = new Intent(mContext, CloudWebViewActivity.class);
		intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
				.getTaskOrScheduleDetailUrl(t.taskIdOrEventId));
		MonitorParam monitorParam = new MonitorParam(
				new String[] { "m=delete" }, WebSyncDefaultProxy.STEP_START,
				new String[] { "taskcondition=today", "m=list&objid=task",
						"eventcondition=today" }, true,
				WebSyncDefaultProxy.STEP_START);
		MonitorParam monitorParam2 = new MonitorParam(
				new String[] { "m=save" }, WebSyncDefaultProxy.STEP_START,
				new String[] { "m=query" }, true,
				WebSyncDefaultProxy.STEP_OVERRIDEURL);
		MonitorParam monitorParam3 = new MonitorParam(new String[] {
				"taskcondition=today", "eventcondition=today" },
				WebSyncDefaultProxy.STEP_START, new String[] {
						"taskcondition=today", "eventcondition=today" }, true,
				WebSyncDefaultProxy.STEP_START);
		monitorParam3.isCallBack = false;
		intent.putExtra(
				"callback",
				WebSyncDefaultProxy
						.creatDefaultProxy(
								ReceiverConstant.RECEIVE_REFRESH)
						.addMonitorParam(monitorParam)
						.addMonitorParam(monitorParam2)
						.addMonitorParam(monitorParam3).addHomeMonitor());

		startActivity(intent);
	}

	@Override
	public void onClickLink(DynamicModel t) {
		Intent intent = new Intent(mContext, MyWebActivity.class);
		intent.putExtra(IWebView.KEY_URL, t.linkValue);
		intent.putExtra(IWebView.KEY_NAME,
				StringUtils.isBlank(t.linkName) ? "分享链接" : "分享链接-" + t.linkName);
		mContext.startActivity(intent);
	}

	class Ddialog {
		private TextView name;
		private Button cancle, sure;
	}

	protected void showDialog(final DynamicModel t, int pos) {
		final Ddialog dd = new Ddialog();
		LayoutInflater inflater = getActivity().getLayoutInflater();
		View layout = inflater.inflate(R.layout.define_deleted, null);
		dd.name = (TextView) layout.findViewById(R.id.titletitle);
		dd.name.setText("确定删除这条微贴吗？");
		final AlertDialog builder = new AlertDialog.Builder(getActivity())
				.create();
		builder.setView(layout);
		builder.show();
		Button cancle = (Button) layout.findViewById(R.id.quxiaocanle);
		cancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.cancel();
			}
		});
		Button sure = (Button) layout.findViewById(R.id.quedingsure);
		sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mControl.delete(t.id);
				mAdapter.removeItem(t);
				builder.cancel();
			}
		});

	}

	@OnClick(R.id.in_know)
	public void clickKnow() {
		mmm.setVisibility(View.GONE);
		mRefreshLayout.setVisibility(View.VISIBLE);
		UserManager.getManager().saveFrist(false);
	}

	@Override
	public void onResume() {
		super.onResume();
		isFirst();
		register();
	}

	@Override
	public void onPause() {
		super.onPause();
		mRefreshLayout.refreshComplete();

	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

	private void isFirst() {

		if (hasCheckFrist) {
			return;
		}
		if (UserManager.getManager().isFrist()) {
			mmm.setVisibility(View.VISIBLE);
			mRefreshLayout.setVisibility(View.GONE);
		} else {
			mmm.setVisibility(View.GONE);
			mRefreshLayout.setVisibility(View.VISIBLE);
		}
		hasCheckFrist = true;
	}

	@Override
	public void onRefreshBegin(PtrFrameLayout arg0) {
		onRefreshData();
	}

	@Override
	public boolean checkCanDoRefresh(PtrFrameLayout frame, View content,
			View header) {
		return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView,
				header);
	}

	private class MyHeader extends MaterialHeader {

		public MyHeader(Context context) {
			super(context);
		}

		public MyHeader(Context context, AttributeSet attrs, int defStyleAttr) {
			super(context, attrs, defStyleAttr);
		}

		public MyHeader(Context context, AttributeSet attrs) {
			super(context, attrs);
		}

		@Override
		public void onUIRefreshComplete(PtrFrameLayout frame) {
			super.onUIRefreshComplete(frame);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		DynamicModel t = mAdapter.getItem(position);
		MyChatter covertBean = GsonUtil.covertBean(t, MyChatter.class);
		Intent intent = new Intent(getActivity(), DynamicActivity.class);
		intent.putExtra("myChatter", covertBean);
		startActivity(intent);
	}

	@Override
	public int getLayoutId() {
		return R.layout.dynamic_frag;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unRegister();
	}

	/**
	 * 发送消息
	 * 
	 * @param event
	 */
	public void onEventMainThread(RefreshDynamicListEvent event) {
		initRequestData();
	}
}
